package com.alesj.newsfeed.file.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

import com.alesj.newsfeed.file.AttachmentHandler;
import com.alesj.newsfeed.file.ByteAdapter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author <a href="mailto:ales.justin@jboss.com">Ales Justin</a>
 */
public class DiskAttachmentHandler implements AttachmentHandler<File> {

    private Log log = LogFactory.getLog(getClass());

    private File root;
    private long timestamp;

    public void saveAttachments(String rootId, List<? extends ByteAdapter> files) throws Exception {
        File msgDir = new File(root, rootId);
        if (msgDir.exists())
            throw new IllegalArgumentException("Directory already exists: " + msgDir);
        if (msgDir.mkdir()) {
            log.info("Saving attachments (" + files.size() + ") to " + msgDir + ".");
            for(ByteAdapter ba : files) {
                File attachment = new File(msgDir, ba.getName());
                FileOutputStream fos = new FileOutputStream(attachment);
                try {
                    fos.write(ba.getBytes());
                } finally {
                    fos.close();
                }
            }
        } else {
            throw new IllegalArgumentException("Cannot create directory: " + msgDir);
        }
    }

    public void removeAttachments() {
        File[] dirs = root.listFiles();
        long now = System.currentTimeMillis();
        for(File attDir : dirs) {
            if (attDir.isDirectory() && attDir.lastModified() + timestamp < now) {
                log.info("Removing attachments from " + attDir + ".");
                delete(attDir);
            }
        }
    }

    public File[] getAttachments(String rootId) {
        File msgDir = new File(root, rootId);
        return msgDir.listFiles();
    }

    protected void delete(File root) {
        if (root.isFile()) {
            root.delete();
        } else {
            File[] files = root.listFiles();
            for(File f : files) {
                delete(f);
            }
            root.delete();
        }
    }

    public void setRoot(File root) {
        this.root = root;
    }

    public void setTimestamp(long timestamp) {
        this.timestamp = timestamp;
    }

    public void setTimestampString(String ts) {
        String[] s = ts.split("\\*");
        timestamp = 1;
        for(String k : s) {
            timestamp *= Long.parseLong(k);
        }
    }
}
